package cn.edu.ecut.request;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;

@WebServlet( "/request/data/servlet" )
public class RequestDataServlet extends HttpServlet {

    @Override
    protected void service( HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {
        request.setCharacterEncoding( "UTF-8" );
        response.setCharacterEncoding( "UTF-8" );

        // HTTP 请求行 : 方法  URI  协议
        String method = request.getMethod();
        String uri = request.getRequestURI(); // URI : 统一资源标识符
        String protocol = request.getProtocol();

        String qs = request.getQueryString();
        qs = qs == null ? "" : qs ;

        System.out.println( method + " " + uri + "?" + qs + " " + protocol );

        // 请求头
        Enumeration<String> headerNames = request.getHeaderNames(); // 获取所有的请求头字段名称
        while( headerNames.hasMoreElements() ){
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader( headerName ) ; // 根据 请求头字段名称 获取 字段值
            System.out.println( headerName + ":" + headerValue );
        }

        System.out.println();

        // 以流的形式读取请求体中的数据 ( request.getInputStream() 可以返回字节流 )
        BufferedReader br = request.getReader(); // 以字符流形式返回

        String s ;
        while( ( s = br.readLine() ) != null ){
            System.out.println( s );
        }

    }

}
